package messages.elevator;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import state.Globals;
import state.group.ElevatorStruct;
import messages.BaseMessage;
import messages.MessageType;
import messages.MessageUtils;

public class ElevatorStatusMessage extends BaseMessage {
    
    ElevatorStruct struct;

    public ElevatorStatusMessage(byte[] data)
    {
        super(data);
        
        this.struct = new ElevatorStruct();
        
        struct.identifier = data[1];
        struct.udpPort = MessageUtils.parseInt(data, 2);
        struct.doorOpen = data[6];
        struct.lastKnownFloor = data[7];
        struct.ticksToNextFloor = data[8];
        struct.direction = data[9];
        struct.curDestination = data[10];
        
        struct.currentWeight = MessageUtils.parseInt(data, 11);
        
        for (int i = 0;i < struct.destinations.length;i++)
        {
            struct.destinations[i] = data[15 + i];
        }
        
    }
    
    public ElevatorStatusMessage(ElevatorStruct struct)
    {
        super(null);
        
        this.struct = struct;
    }

    @Override
    public byte[] toByteArray()
    {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        
        output.write(getMessageType().getIdentifier());
        output.write(struct.identifier);
        
        byte[] intBuf = new byte[4];
        MessageUtils.insertInt(intBuf, 0, struct.udpPort);
        
        try {
			output.write(intBuf);
		} catch (IOException e) {
		    Globals.getLogger().error("Error writing to ByteArrayOutputStream, shouldn't happen", e);
		}
        
        output.write(struct.doorOpen);
        output.write(struct.lastKnownFloor);
        output.write(struct.ticksToNextFloor);
        output.write(struct.direction);
        output.write(struct.curDestination);
        
        MessageUtils.insertInt(intBuf, 0, struct.currentWeight);
        try {
			output.write(intBuf);
		} catch (IOException e) {
		    Globals.getLogger().error("Error writing to ByteArrayOutputStream, shouldn't happen", e);
		}
        
        for (int i = 0;i < struct.destinations.length;i++)
        {
            output.write(struct.destinations[i]);
        }
        
        return output.toByteArray();
    }

    @Override
    public MessageType getMessageType()
    {
        return MessageType.ElevatorStatusMessage;
    }
    
    public ElevatorStruct getElevatorStruct()
    {
        return struct;
    }

    @Override
    public int getMessageSize()
    {
        return 15 + ElevatorStruct.MAX_FLOORS;
    }

}
